<template>
  <div class="app-container">

    <el-card class="box-card">
      <el-form :rules="rules" ref="ruleForm" :model="ruleForm" label-width="150px" v-loading='loading'>

        <el-form-item label="缩略图" prop="suolueImg">
          <el-upload :headers="headers" :data='{dirName:""}' :limit="1" list-type="picture-card" :action="uploadPath" :on-remove="handleRemoveImg" :on-success="handleAvatarSuccess" :on-error="handleErrorImg" :on-change="beforeAvatarUpload" :before-upload="allImgBeforeUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="文件地址：">
          <!-- <el-upload :headers="headers" :data='{dirName:""}' :limit="1" :on-remove="handleRemoveFile" :action="uploadPath" :on-success="handleFileSuccess" :on-error="handleErrorFile">
            <i class="el-icon-plus"></i>
          </el-upload> -->
          <el-input v-model="ruleForm.downUrl" />
        </el-form-item>

        <el-form-item label="一级分类选择：">
          <el-select @change="bingclassifyNoe" v-model="PClassId" placeholder="请选择">
            <el-option v-for="item in PClass" :key="item.id" :label="item.names" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类选择：" prop="typeId">
          <el-select @change="bingclassifyTow" v-model="ruleForm.typeId" placeholder="请选择">
            <el-option v-for="item in SunClass" :key="item.id" :label="item.names" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="素材名称：" prop="soureName">
          <el-input v-model="ruleForm.soureName" />
        </el-form-item>
        <el-form-item label="素材价格：" prop="prices">
          <el-input-number v-model="ruleForm.prices" :min="0"></el-input-number> 0为显示免费 大于5000显示联系客服
        </el-form-item>
        <el-form-item label="素材格式：" prop="soureFormat">
          <el-input v-model="ruleForm.soureFormat" />
        </el-form-item>
        <el-form-item label="点击率：" prop="clickNum">
          <el-input-number v-model="ruleForm.clickNum" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="联系方式：" prop="contactPro">
          <el-input v-model="ruleForm.contactPro" />
        </el-form-item>

        <el-form-item label="素材简介：" prop="soureDesc">
          <el-input v-model="ruleForm.soureDesc" />
        </el-form-item>

        <el-form-item label="素材详细" prop="soureDetails">
          <div style="border: 1px solid #ccc; margin-top: 10px;">
            <!-- 工具栏 -->
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
            <!-- 编辑器 -->
            <Editor style="height: 400px; overflow-y: hidden;" :defaultConfig="editorConfig" v-model="ruleForm.soureDetails" @onChange="onChange" @onCreated="onCreated" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button :loading='loading' type="primary" @click="handlePublish">保存</el-button>
        </el-form-item>

      </el-form>
    </el-card>

  </div>
</template>



<script>
import api from '@/api/material/goods'
import storage, { uploadPath } from '@/api/storage'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getToken } from '@/utils/auth'
import utils from '@/utils/watermark'
import '@wangeditor/editor/dist/css/style.css'
import Element from 'element-ui'
export default {
  name: 'GoodsCreate',
  components: { Editor, Toolbar },

  data() {
    return {
      editor: null,
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      editorConfig: {
        placeholder: '请输入内容...',
        // autoFocus: false,

        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          uploadImage: {
            server: uploadPath,
            fieldName: 'file',
            headers: {
              'X-Hyxxkj-Admin-Token': getToken()
            },
            meta: {
              dirName: ''
            },

            async customUpload(file, insertFn) {
              const isLt2M = file.size / 1024 / 1024 < 3
              let isType = false
              if (
                file.type == 'image/png' ||
                file.type == 'image/jpeg' ||
                file.type === 'image/gif' ||
                file.type === 'image/bmp'
              ) {
                isType = true
              }
              if (!isType) {
                Element.Message.error('上传图片只能是 JPG/PNG/GIF/BMP 格式!')
                return
              }
              if (!isLt2M) {
                Element.Message.error('上传图片大小不能超过 3MB!')
                return
              }
              function foo() {
                return utils
                  .transformFile(file)
                  .then((res) => {
                    return res
                  })
                  .catch((error) => {})
              }
              var newImg = await foo()
              const formData = new FormData()
              formData.append('file', newImg)
              formData.append('dirName', '')
              storage.createStorage(formData).then((res) => {
                if (res.data.errno == 0) {
                  insertFn(
                    res.data.data.url,
                    res.data.data.name,
                    res.data.data.url
                  )
                } else {
                  this.$message.error(`${file.name} 上传出错`)
                }
              })
            },
            onSuccess: () => {},
            onError: (file, err, res) => {
              this.$message.error(`${file.name} 上传出错`)
            }
          },
          uploadVideo: {
            server: uploadPath,
            fieldName: 'file',
            headers: {
              'X-Hyxxkj-Admin-Token': getToken()
            },
            meta: {
              dirName: ''
            },
            onError: (file, err, res) => {
              this.$message.error(`${file.name} 上传出错`)
            }
          }
        }
      },
      fileList: [],
      loading: false,
      uploadPath: uploadPath,
      PClassId: '',
      PClass: [],
      SunClassId: '',
      SunClass: [],
      classALL: '',
      ruleForm: {
        soureName: '',
        prices: '',
        soureFormat: '',
        soureDetails: '',
        clickNum: 0,
        contactPro: '',
        soureDesc: '',
        soureDetails: '',
        prices: '',
        // weboss:"",
        suolueImg: '', // 缩略图地址
        typeId: '',
        downUrl: ''
      },
      rules: {
        soureName: [
          { required: true, message: '请输入素材名称', trigger: 'blur' }
        ],
        prices: [
          { required: true, message: '请输入素材价格', trigger: 'blur' }
        ],
        soureDesc: [
          { required: true, message: '请输入素材简介', trigger: 'blur' }
        ],
        soureDetails: [
          { required: true, message: '请输入素材详情', trigger: 'blur' }
        ],

        typeId: [
          { required: true, message: '请选择二级分类', trigger: 'change' }
        ],

        suolueImg: [
          { required: true, message: '请上传缩略图', trigger: 'change' }
        ],

        downUrl: [{ required: true, message: '请上传文件', trigger: 'change' }]
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Hyxxkj-Admin-Token': getToken()
      }
    }
  },
  created() {},
  mounted() {
    api
      .typeList({
        limit: 1000,
        page: 1
      })
      .then((res) => {
        this.classALL = res.data.data.list
        res.data.data.list.map((item) => {
          this.PClass.push(item.PClass)
        })
      })
  },
  methods: {
    bingclassifyNoe(e) {
      this.SunClass = []
      this.ruleForm.typeId = ''
      for (let i = 0; i < this.classALL.length; i++) {
        if (this.classALL[i].PClass.id == e) {
          this.SunClass = this.classALL[i].SunClass
          return
        }
      }
    },
    bingclassifyTow(e) {},
    onCreated(editor) {
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
    },
    onChange(editor) {
      //  console.log('onChange', editor.getHtml()) // onChange 时获取编辑器最新内容
    },
    handleRemoveFile() {
      this.ruleForm.downUrl = ''
    },
    handleErrorFile() {
      this.ruleForm.downUrl = ''
      this.$message.error('文件上传出错')
    },
    handleErrorImg() {
      this.ruleForm.suolueImg = ''
      this.$message.error('图片上传出错')
    },
    handleRemoveImg() {
      this.ruleForm.suolueImg = ''
    },
    handleAvatarSuccess(res, file) {
      if (res.errno == 0) {
        this.ruleForm.suolueImg = res.data.url
      }
    },
    allImgBeforeUpload(file) {
      var isJPG = false
      var self = this
      if (
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/bmp'
      ) {
        isJPG = true
      }

      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF/BMP 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }

      //   return isJPG && isLt2M

      if (file.type == 'image/gif') {
        var createObjectURL = function(blob) {
          return window[window.webkitURL ? 'webkitURL' : 'URL'][
            'createObjectURL'
          ](blob)
        }

        return new Promise((resole, reject) => {
          const img = new Image()
          img.onload = function() {
            if (img.width > 500 || img.height > 600) {
              self.$message.error('缩略图尺寸不对')
              reject(false)
            } else {
              resole(true)
            }
          }
          img.src = createObjectURL(file)
        })
      } else {
        var fileType = file.type
        if (fileType.includes('image')) {
          var uid = file.uid
          return new Promise((resolve, reject) => {
            utils
              .transformFile(file, true)
              .then((res) => {
                res.uid = uid
                resolve(res)
              })
              .catch((error) => {
                reject(error)
              })
          })
        }
      }
    },
    handleFileSuccess(res, file) {
      if (res.errno == 0) {
        this.ruleForm.downUrl = res.data.url
      }
    },
    beforeAvatarUpload(file) {},

    handleCancel: function() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push({ path: './list' })
    },
    handlePublish() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.versionCreate(this.ruleForm)
          // this.$refs.uploadIMG.submit()
        } else {
          this.$message({
            message: '请检查数据必填项',
            type: 'warning'
          })
          return false
        }
      })
    },

    versionCreate(e) {
      this.loading = true
      api
        .create(e)
        .then((res) => {
          if (res.data.errno == 0) {
            this.loading = false
            this.$message({
              message: '新增成功',
              type: 'success'
            })
            this.$router.push({ path: './list' })
          }
        })
        .catch(() => {
          this.loading = false
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px solid #dcdc;
}
.avatar {
  width: 178px;
  height: 178px;
}
</style>